<?php

class SalesOrderPaymentConvertUtil extends CComponent
{

    public function convertSalesOrderPaymentToInvoicePayment($salesOrderNumber, $invoiceNumber, $jobNumber)
    {
        if ($this->isSalesOrderAndInvoiceBelongSameJob($salesOrderNumber, $invoiceNumber, $jobNumber)
                && $this->isInvoiceConvertable($invoiceNumber)
                && $this->isSalesOrderConvertable($salesOrderNumber))
        {
            return $this->doConvertSalesOrderPaymentToInvoicePayment($salesOrderNumber, $invoiceNumber, $jobNumber);
        }
        return false;
    }

    public function doConvertSalesOrderPaymentToInvoicePayment($salesOrderNumber, $invoiceNumber, $jobNumber)
    {
        $salesOrderModel    = Invoice::model()->findByPk($salesOrderNumber);
        $invoiceModel       = Invoice::model()->findByPk($invoiceNumber);
        $jobModel           = Jobs::model()->findByPk($jobNumber);
        if($jobModel!=null && $salesOrderModel!=null && $invoiceModel!=null){
            //create new REC model
            //calculate amount to fill
            $amountCharge   = $this->getConvertAmount($salesOrderNumber, $invoiceNumber);
            $recModel=Rec::model()->find('invoice=:invoice',array(
                'invoice'   => $invoiceNumber
            ));
            if($recModel==null){
                $recModel   = new Rec();
            }            
            $recModel->invoice  = $invoiceNumber;
            $recModel->transid  = createRandomUUID();
            $recModel->custno   = $invoiceModel->custno;            
            $recModel->invamt   = $amountCharge;
            $recModel->paid     = 0;
            $recModel->invdate  = $invoiceModel->invoicedate;
            $recModel->transid  = $transid;
            $recModel->dept     = $invoiceModel->department;
            $recModel->locno    = $invoiceModel->locno;
            $recModel->type     = 'I';
            $recModel->acct     = '1110';
            $recModel->period   = $invoiceModel->period;            
        }
        return false;
    }
    
    protected function getConvertAmount($salesOrderNumber,$invoiceNumber)
    {
        //sales order rec led amount - invoice current amount
        //if result < 0 return SO amount else return INV amount
        //after that, need to update, amount = current
        $salesOrderAmount   = Yii::app()->db
                ->createCommand('select sum(paid) from tbl_rec_led_apply where number=:number')
                ->bindValues(array(
                    'number' => $salesOrderNumber
                ))
                ->queryScalar();
        $invoiceAmount      = Yii::app()->db
                ->createCommand('select invamt - paid from tbl_rec where invoice=:number')
                ->bindValues(array(
                    'number' => $invoiceNumber
                ))
                ->queryScalar();
        $amount             = 0;
        return abs($invoice - $salesOrderAmount);
    }
    protected function updateSalesOrderRecLedAmount($salesOrderNumber,$amount)
    {        
        $salesOrderRecLedList   = RecLedApply::model()->findAll('number=:number',array(
            'number'=>$salesOrderNumber
        ));
        $remainAmount           = $amount;
        foreach($salesOrderRecLedList as $recLedApply)
        {            
            $remainAmount -= $recLedApply->paid;
            if($remainAmount>0)
            {
                $recLedApply->paid = 0;
            }
            else
            {
                $recLedApply->paid = abs($remainAmount);
            }
            $recLedApply->save();
        }
    }    
    public function isSalesOrderAndInvoiceBelongSameJob($salesOrderNumber, $invoiceNumber, $jobNumber)
    {
        $salesOrder = Yii::app()->db
                ->createCommand('select * from tbl_invoice where invoice=:salesOrderNumber AND invoicetype=:invoiceType')
                ->bindValues(array(
                    'salesOrderNumber'  => $salesOrderNumber,
                    'invoiceType'       => Invoice::TYPE_SALES_ORDERS
                ))
                ->queryRow();
        $invoice = Yii::app()->db
                ->createCommand('select * from tbl_invoice where invoice=:invoiceNumber AND invoicetype=:invoiceType')
                ->bindValues(array(
                    'invoiceNumber'     => $invoiceNumber,
                    'invoiceType'       => Invoice::TYPE_INVOICE
                ))
                ->queryRow();
        if ($salesOrder != null 
                && $invoice != null
                && $salesOrder['jobnumber'] = $invoice['jobnumber'])
        {
            return true;
        }
        return false;
    }

    public function isSalesOrderConvertable($salesOrderNumber)
    {
        assert('is_string($salesOrderNumber)');
        $exist = Yii::app()->db
                ->createCommand('select count(i.invoice) from tbl_invoice i
                                 left join tbl_rec_led_apply r on r.number = i.invoice
                                 where i.invoice=:number and i.invoicetype=:invoiceType and r.paid>0')
                ->bindValues(array(
                    'number'            => $salesOrderNumber,
                    'invoiceType'       => Invoice::TYPE_SALES_ORDERS,
                ))
                ->queryScalar();
        if (is_numeric($exist) && $exist > 0)
        {
            return true;
        }
        return false;
    }

    public function isInvoiceConvertable($invoice)
    {
        $invoice = Yii::app()->db
                ->createCommand('select i.* from tbl_invoice i
                                 left join tbl_jobs j on i.jobnumber = j.jobid
                                 left join tbl_rec r on r.invoice = i.invoice
                                 where i.jobnumber =:jobNumber AND r.paidoff is null AND i.invoice=:invoiceNumber')
                ->bindValues(array(
                    'jobNumber'     => $jobNumber,
                    'invoiceNumber' => $invoice
                ))
                ->queryRow();
        if ($invoice != null)
        {
            return true;
        }
        return false;
    }

    public function getInvoiceListFromJob($jobNumber)
    {
      
        $list=Invoice::model()->findAll(array(
            'alias'=>'i',
            'join'=>'left join tbl_jobs j on i.jobnumber = j.jobid
                     left join tbl_rec r on r.invoice = i.invoice',
            'condition'=>'i.jobnumber =:jobNumber AND r.paidoff is null AND i.invoicetype=:invoiceType',
            'params'=>array(
                    'jobNumber'     => $jobNumber,
                    'invoiceType'   => Invoice::TYPE_INVOICE
                )
        ));
        if (count($list) > 0)
        {
            return $list;
        }
        return false;
    }

}

?>
